package com.wlz.framework.protocol.dubbo;

import com.wlz.framework.Invocation;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.serialization.ClassResolvers;
import io.netty.handler.codec.serialization.ObjectDecoder;
import io.netty.handler.codec.serialization.ObjectEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author wlz
 * @date 2022-07-11  10:13 下午
 */
@Slf4j
public class NettyClient<T> {

    public NettyClientHandler clientHandler = null;

    private static ExecutorService executorService = Executors.newCachedThreadPool();

    public void start(String hostname , Integer port) {
        clientHandler = new NettyClientHandler();

        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();

            bootstrap.group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .option(ChannelOption.TCP_NODELAY, true)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            socketChannel.pipeline().addLast("decoder", new ObjectDecoder(
                                    ClassResolvers.weakCachingConcurrentResolver(this.getClass().getClassLoader())));
                            socketChannel.pipeline().addLast("encoder", new ObjectEncoder());
                            socketChannel.pipeline().addLast("handler", clientHandler);
                        }
                    });

            log.info("dubbo netty client  start .....");
            bootstrap.connect(hostname, port).sync();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String send(String hostname, Integer prot, Invocation invocation) {
        if (clientHandler == null) {
            start(hostname, prot);
        }
        clientHandler.setInvocation(invocation);

        try {
            return (String) executorService.submit(clientHandler).get();
        } catch (InterruptedException e) {
//            e.printStackTrace();
        } catch (ExecutionException e) {
//            e.printStackTrace();
        }

        return null;
    }


    public void close() {

    }
}
